package algorithm.leetcode.I1to100;

import java.util.LinkedList;
import java.util.List;

/**
 * 剑指offer 29题
 */

public class Q54 {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new LinkedList<>();
        int left = 0, right = matrix[0].length-1, cell = 0, floor = matrix.length-1;

        while (true) {
            for (int i = left; i <= right; i++) list.add(matrix[cell][i]);
            cell++;
            if (cell > floor) break;

            for (int i = cell; i <= floor; i++) list.add(matrix[i][right]);
            right--;
            if (right < left) break;

            for (int i = right; i >= left; i--) list.add(matrix[floor][i]);
            floor--;
            if (cell > floor) break;

            for (int i = floor; i >= cell; i--) list.add(matrix[i][left]);
            left++;
            if (right < left) break;

        }
        return list;
    }

}
